import React, {useEffect, useState, useRef}from "react";
import {Table, Pagination, Input, Button, message, Popconfirm, Space, Card, Drawer} from 'antd';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import moment from 'moment';
import {connect} from 'umi';
import ComponentsModal from "@/pages/transaction-detail/components/ComponentsModal";
import {getPageInfoList, getRemoteList} from './service';

//时间格式化
const formatterDateTime = (val) => {
  return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
}

interface ActionType {
  reload: () => void;
  fetchMore: () => void;
  reset: () => void;
}

const index = ({TransactionDetail, dispatch, TransactionLoading}) =>{

  const columns = [
    {
      title: '交易id',
      dataIndex: 'transId',
      disEdit: true,
      isAuto: true,
      align: 'center',
    },
    {
      title: '客户id',
      disEdit: true,
      dataIndex: 'custId',
      align: 'center',
    },
    {
      title: '账户号',
      dataIndex: 'account',
      align: 'center',
    },
    {
      title: '卡号',
      dataIndex: 'cardNbr',
      align: 'center',
    },
    {
      title: '交易流水号',
      dataIndex: 'tranno',
      align: 'center',
    },
    {
      title: '账单月',
      dataIndex: 'monthNbr',
      align: 'center',
    },
    {
      title: '交易金额',
      dataIndex: 'bill',
      align: 'center',

    },
    {
      title: '交易类型',
      dataIndex: 'transType',
      align: 'center',
      options: [{
        value: '还款',
        text: '还款'
      },{
        value: '消费',
        text: '消费'
      }],
      inputType: 'select',
    },
    {
      title: '交易时间',
      dataIndex: 'txnDatetime',
      inputType: 'date',
      align: 'center',
      render: formatterDateTime

    },{
      title: '操作',
      disShow: true,
      align: 'center',
      render: (text, record, index) => {
        return (
          <div>
            <Button type="primary"
                    style={{marginLeft:"1rem"}}
                    size={"small"}
                    onClick={() =>{
                      showForm(record)
                    }}
            >修改</Button>
            <Popconfirm
              title={"确定删除？"}
              onCancel={()=>message.error('用户取消删除操作')}
              onConfirm={()=> {
                console.log('删除提交数据！: ', record.transId);
                dispatch({
                  // namespace 的名字/ 指定函数 edit
                  type: 'TransactionDetail/delete',
                  payload: {record},
                });
                // ref.current.reload();
              }}
              //改变按钮名字
              okText="是"
              cancelText="否"
            >
              <Button type="primary" danger style={{marginLeft:"1rem"}} size={"small"}>
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      }
    }
  ];
  const [visible, setVisible] = useState(false);
  const [record, setRecord] = useState([]);
  const [isEdit, setIsEdit] = useState(true);
  const formRules = {
    'transId': [{
      required: true,
      message: `请输入交易id`
    }
    ],
    'custId': [{
      required: true,
      message: `请输入客户id`
    }, {
      pattern: new RegExp(/^[1-9]\d*$/, "g"),
      message: '请输入数字'
    },{
      max: 11,
      message: '最大长度为11'
    }
    ],
    'account': [{
      required: true,
      message: `请输入账户号`
    },{
      max: 10,
      message: '最大长度为10'
    },{
      pattern: new RegExp(/^[1-9]\d*$/, "g"),
      message: '请输入数字'
    }],
    'cardNbr': [{
      required: true,
      message: `请输入卡号`
    },{
      pattern: new RegExp(/^[1-9]\d*$/, "g"),
      message: '请输入数字'
    },{
      max: 16,
      message: '最大长度为16'
    }],
    'tranno': [{
      required: true,
      message: `请输入交易流水号`
    },{
      pattern: new RegExp(/^[1-9]\d*$/, "g"),
      message: '请输入数字'
    },{
      type: "string",
      max: 11,
      message: '最大长度为11'
    }],
    'monthNbr': [{
      required: true,
      message: `请输入账单月`
    },{
      pattern: new RegExp(/^[1-9]\d*$/, "g"),
      message: '请输入数字'
    },{
      type: "string",
      max: 11,
      message: '最大长度为11'
    }],
    'bill': [{
      required: true,
      message: `请输入交易金额`
    },{
      type: "string",
      max: 11,
      message: '最大长度为11'
    }],
    'transType': [{
      required: true,
      message: `请输入交易类型`
    },{
      type: "string",
      max: 30,
      message: '最大长度为30'
    }],
    'txnDatetime': [{
      required: true,
      message: `请输入交易日期`
    }]
  }
  const ref = useRef<ActionType>();

  function showForm (record) {
    setIsEdit(true);
    setVisible(true);
    setRecord(record);
  }

  const onSubmit = values => {
    console.log('新建/编辑提交数据！: ', values);
    //传到 model 里面
    dispatch({
      // namespace 的名字/ 指定函数 edit/add
      type: `TransactionDetail/${values.transId ? 'edit': 'add'}`,
      payload: {values},
    });

    setVisible(false);
    // ref.current.reload();
  }

  const addHandler = () => {
    setIsEdit(false);
    setVisible(true);
  }

  const requestHandler = async ({pageSize,current}) => {
    //仓库获取数据之前就调用了，与仓库之间无联系
    console.log("调用request：", pageSize,current);
    const data = await getPageInfoList(current, pageSize);
    return {
      data: data.list,
      success: true,
      total: data.total,
    }
  }

  const paginationHandler = (pageNum, pageSize) => {
    console.log("调用PaginationHandler：", pageSize, pageNum);
    dispatch({
      type: 'TransactionDetail/getPageInfoRemote',
      payload: {
        pageNum,
        pageSize,
      },
    });
  }

  const reloadHandler = () => {
    dispatch({
      type: 'TransactionDetail/getPageInfoRemote',
      payload: {
        pageNum: TransactionDetail.data.pageNum,
        pageSize: TransactionDetail.data.pageSize,
      },
    });
  }

  return(
    <div className={"list-table"}>
      <ProTable rowKey="transId"
             headerTitle={"交易信息表！"}
             toolBarRender={()=> [
               <Button type="primary" onClick={addHandler} >
                 添加
               </Button>
             ]}
             columns={columns}
             dataSource={TransactionDetail.data.list}
             loading={TransactionLoading}
             bordered
             search={false}
             pagination={false}
             options={{
               density: true,
               fullScreen: true,
               setting: true,
               reload: ()=>{
                 reloadHandler()
              }

             }}
             // request={requestHandler}
             // actionRef={ref}
      />
      <Pagination
        className={"list-page"}
        total={TransactionDetail.data.total}
        onChange={paginationHandler}
        pageSizeOptions={['5' , '10', '20', '50', '100']}
        showSizeChanger
        showQuickJumper
        showTotal={total => `Total ${total} items`}
      />
      <ComponentsModal
        title={"新建交易信息"}
        columns={columns}
        record={record}
        formRules={formRules}
        visible={visible}
        onSubmit={onSubmit}
        isEdit={isEdit}
        onCancel={() => {
          setVisible(false);
        }}
      />
    </div>
  );
};

//const mapStateToProps = (state) 原来是state，取里面的state.TransactionDetail
//进一步可以省为const mapStateToProps = ({TransactionDetail}) => ({TransactionDetail})
const mapStateToProps = ({TransactionDetail, loading}) => {
  console.log("Loading状态: ", loading.models.TransactionDetail);
  return{
    TransactionDetail,
    TransactionLoading: loading.models.TransactionDetail,
  };
}

//可以省写为export default connect(({TransactionDetail}) => ({
//    TransactionDetail,
// }))(index);
export default connect(mapStateToProps)(index);
